#include "../include/widget.h"
#include "../ui_set/ui_widget.h"
#include"../include/pieview.h"
#include<QSqlQueryModel>
#include<QSqlQuery>
#include<QSplitter>
#include<QMessageBox>
#include<QDateTime>
#include<QFile>
#include<QStandardItemModel>
#include<QTableView>
#include<QRandomGenerator>
#include<QColor>
#include<QMouseEvent>

Widget::Widget(QWidget *parent)
    : QMainWindow(parent), ui(new Ui::Widget)
{
    ui->setupUi(this);
    this->createMenuBar();

    this->setFixedSize(750,500);
    ui->stackedWidget->setCurrentIndex(0);
    QSqlQueryModel *factoryModel=new QSqlQueryModel(this);
    factoryModel->setQuery("select name from factory");
    ui->sellFactoryComboBox->setModel(factoryModel);
    QSplitter *splitter=new QSplitter(ui->managerPage);
    splitter->resize(700,360);
    splitter->move(0,50);
    splitter->addWidget(ui->toolBox);
    splitter->addWidget(ui->dailyList);
    splitter->setStretchFactor(0,1);
    splitter->setStretchFactor(1,1);

    this->showDailyList();

    ui->factoryComboBox->setModel(factoryModel);
    this->createChartModelView();

}

Widget::~Widget()
{
    delete ui;
}

const QString Widget::getDateTime(const DateTimeType &type)
{
    QDateTime dateTime=QDateTime::currentDateTime();
    QString date=dateTime.toString("yyyy-MM-dd");
    QString time=dateTime.toString("hh:mm:ss");
    QString dateAndTime=dateTime.toString("yyyy-MM-dd hh:mm:ss");
    if(type==Date)  return date;
    else if(type==Time) return time;
    else return dateAndTime;
}

void Widget::manageMenu_clicked()
{
    ui->stackedWidget->setCurrentIndex(0);
}

void Widget::chartMenu_clicked()
{
    ui->stackedWidget->setCurrentIndex(1);
}

void Widget::quitMenu_clicked()
{
    this->close();
}

void Widget::createMenuBar()
{
    manageAction=new QAction(tr("品牌车管理"),this);
    chartAction=new QAction(tr("销售统计"),this);
    quitAction=new QAction(tr("退出"),this);
    manageAction->setShortcut(tr("Ctrl+m"));
    chartAction->setShortcut(tr("Ctrl+c"));
    quitAction->setShortcut(tr("Ctrl+q"));

    manageMenu=menuBar()->addMenu(tr("销售管理"));
    manageMenu->addAction(manageAction);
    manageMenu->addAction(chartAction);
    manageMenu->addSeparator();
    manageMenu->addAction(quitAction);
    passWordMenu=menuBar()->addMenu(tr("修改密码"));
    connect(manageAction,SIGNAL(triggered(bool)),this,SLOT(manageMenu_clicked()));
    connect(chartAction,SIGNAL(triggered(bool)),this,SLOT(chartMenu_clicked()));
    connect(quitAction,SIGNAL(triggered(bool)),this,SLOT(quitMenu_clicked()));
}

void Widget::createChartModelView()
{
    chartModel=new QStandardItemModel(this);
    chartModel->setColumnCount(2);
    chartModel->setHeaderData(0,Qt::Horizontal,QString("品牌"));
    chartModel->setHeaderData(1,Qt::Horizontal,QString("销售数量"));
    QSplitter *splitter=new QSplitter(ui->chartPage);
    splitter->resize(700,320);
    splitter->move(0,80);
    QTableView *table=new QTableView;
    PieView *pieChart=new PieView;
    splitter->addWidget(table);
    splitter->addWidget(pieChart);
    splitter->setStretchFactor(0,1);
    splitter->setStretchFactor(1,2);
    table->setModel(chartModel);
    pieChart->setModel(chartModel);
    QItemSelectionModel *selectionModel=new QItemSelectionModel(chartModel);
    table->setSelectionModel(selectionModel);
    pieChart->setSelectionModel(selectionModel);
}

void Widget::showChart()
{
    QSqlQuery query;
    query.exec(QString("select name,sell from brand where factory='%1'").arg(ui->factoryComboBox->currentText()));
    chartModel->removeRows(0,chartModel->rowCount());
    int row=0;
    QRandomGenerator randomColor=QRandomGenerator::securelySeeded();
    while(query.next()){
        int r=randomColor.bounded(0,256);
        int g=randomColor.bounded(0,256);
        int b=randomColor.bounded(0,256);
        chartModel->insertRows(row,1);
        chartModel->setData(chartModel->index(row,0),query.value(0).toString());
        chartModel->setData(chartModel->index(row,1),query.value(1).toInt());
        chartModel->setData(chartModel->index(row,0),QColor(r,g,b),Qt::DecorationRole);
        row++;
    }
}

const bool Widget::docRead()
{
    QFile file("data.xml");
    if(!file.open(QIODevice::ReadOnly)) return false;
    if(!doc.setContent(&file)){
        file.close();
        return false;
    }
    file.close();
    return true;
}

bool Widget::docWrite()
{
    QFile file("data.xml");
    if(!file.open(QIODevice::WriteOnly|QIODevice::Truncate))
        return false;
    QTextStream out(&file);
    doc.save(out,4);
    file.close();
    return true;
}

void Widget::writeXml()
{
    if(this->docRead()){
        QString currentDate=this->getDateTime(Date);
        QDomElement root=doc.documentElement();
        //根据是否有日期节点进行处理
        if(!root.hasChildNodes()){
            QDomElement date=doc.createElement(QString("日期"));
            QDomAttr curDate=doc.createAttribute("date");
            curDate.setValue(currentDate);
            date.setAttributeNode(curDate);
            root.appendChild(date);
            this->createNodes(date);
        }
        else{
            QDomElement date=root.lastChild().toElement();
            //根据是否已经有今天的日期节点进行处理
            if(date.attribute("date")==currentDate)
                this->createNodes(date);
            else{
                QDomElement date=doc.createElement(QString("日期"));
                QDomAttr curDate=doc.createAttribute("date");
                curDate.setValue(currentDate);
                date.setAttributeNode(curDate);
                root.appendChild(date);
                this->createNodes(date);
            }
        }
        //写入文件
        this->docWrite();
    }
}

void Widget::createNodes(QDomElement &date)
{
    QDomElement time=doc.createElement(QString("时间"));
    QDomAttr curTime=doc.createAttribute("time");
    curTime.setValue(this->getDateTime(Time));
    time.setAttributeNode(curTime);
    date.appendChild(time);
    QDomElement factory=doc.createElement(QString("厂家"));
    QDomElement brand=doc.createElement(QString("品牌"));
    QDomElement price=doc.createElement(QString("报价"));
    QDomElement num=doc.createElement(QString("数量"));
    QDomElement sum=doc.createElement(QString("金额"));
    QDomText text;
    text=doc.createTextNode(QString("%1").arg(ui->sellFactoryComboBox->currentText()));
    factory.appendChild(text);
    text=doc.createTextNode(QString("%1").arg(ui->sellBrandComboBox->currentText()));
    brand.appendChild(text);
    text=doc.createTextNode(QString("%1").arg(ui->sellPriceLineEdit->text()));
    price.appendChild(text);
    text=doc.createTextNode(QString("%1").arg(ui->sellNumSpinBox->value()));
    num.appendChild(text);
    text=doc.createTextNode(QString("%1").arg(ui->sellSumLineEdit->text()));
    sum.appendChild(text);

    time.appendChild(factory);
    time.appendChild(brand);
    time.appendChild(price);
    time.appendChild(num);
    time.appendChild(sum);
}

void Widget::showDailyList()
{
    ui->dailyList->clear();
    if(this->docRead()){
        QDomElement root=doc.documentElement();
        QString title=root.tagName();
        QListWidgetItem *titleItem=new QListWidgetItem;
        titleItem->setText(QString("-----%1-----").arg(title));
        titleItem->setTextAlignment(Qt::AlignCenter);
        ui->dailyList->addItem(titleItem);
        if(root.hasChildNodes()){
            QString currentDate=this->getDateTime(Date);
            QDomElement dateElement=root.lastChild().toElement();
            QString date=dateElement.attribute("date");
            if(date==currentDate){
                ui->dailyList->addItem("");
                ui->dailyList->addItem(QString("日期：%1").arg(date));
                ui->dailyList->addItem("");
                QDomNodeList children=dateElement.childNodes();
                //遍历当日销售的所有汽车
                for(int i=0;i<children.count();i++){
                    QDomNode node=children.at(i);
                    QString time=node.toElement().attribute("time");
                    QDomNodeList list=node.childNodes();
                    QString factory=list.at(0).toElement().text();
                    QString brand=list.at(1).toElement().text();
                    QString price=list.at(2).toElement().text();
                    QString num=list.at(3).toElement().text();
                    QString sum=list.at(4).toElement().text();
                    QString str=time+"出售"+brand+factory+" "+num+"辆，"+"成交价："+price+"万，共"+sum+"万元";
                    QListWidgetItem *tempItem=new QListWidgetItem;
                    tempItem->setText("***************************");
                    tempItem->setTextAlignment(Qt::AlignCenter);
                    ui->dailyList->addItem(tempItem);
                    ui->dailyList->addItem(str);
                }
            }
        }
    }
}

void Widget::on_sellFactoryComboBox_currentTextChanged(const QString &factoryName)
{
    if(factoryName=="请选择厂家")
        on_sellCancelBtn_clicked(false);
    else{
        isCancel=false;
        ui->sellBrandComboBox->setEnabled(true);
        QSqlQueryModel *model=new QSqlQueryModel(this);
        model->setQuery(QString("select name from brand where factory='%1'").arg(factoryName));
        ui->sellBrandComboBox->setModel(model);
        ui->sellCancelBtn->setEnabled(true);
    }
}

void Widget::on_sellCancelBtn_clicked(bool checked)
{
    ui->sellFactoryComboBox->setCurrentIndex(0);
    if(ui->sellBrandComboBox->count()!=0){
        isCancel=true;
        auto model=ui->sellBrandComboBox->model();
        auto sqmodel=qobject_cast<QSqlQueryModel*>(model);
        sqmodel->clear();
    }

    ui->sellPriceLineEdit->clear();
    ui->sellNumSpinBox->setValue(0);
    ui->sellLastNumLabel->setText("000");
    ui->sellSumLineEdit->clear();
    ui->sellCancelBtn->setEnabled(false);

}

void Widget::on_sellBrandComboBox_currentTextChanged(const QString &brandName)
{
    if(isCancel)    return;
    ui->sellNumSpinBox->setValue(0);
    ui->sellNumSpinBox->setEnabled(false);
    ui->sellSumLineEdit->clear();
    ui->sellSumLineEdit->setEnabled(false);
    ui->sellOkBtn->setEnabled(false);

    QSqlQuery query;
    query.exec(QString("select price from brand where name='%1' and factory='%2'").arg(brandName)
                   .arg(ui->sellFactoryComboBox->currentText()));
    query.next();
    ui->sellPriceLineEdit->setEnabled(true);
    ui->sellPriceLineEdit->setReadOnly(true);
    ui->sellPriceLineEdit->setText(query.value(0).toString());
    int num=query.value(0).toInt();
    if(num==0)
        QMessageBox::information(this,tr("提示"),tr("该品牌汽车已经售完"),QMessageBox::Ok);
    else{
        ui->sellNumSpinBox->setEnabled(true);
        ui->sellNumSpinBox->setMaximum(num);
        ui->sellLastNumLabel->setText(tr("剩余数量：%1").arg(num));
        ui->sellLastNumLabel->setVisible(true);
    }
}

void Widget::on_sellNumSpinBox_valueChanged(int num)
{
    if(num==0){
        ui->sellSumLineEdit->clear();
        ui->sellSumLineEdit->setEnabled(false);
        ui->sellOkBtn->setEnabled(false);
    }
    else{
        ui->sellSumLineEdit->setEnabled(true);
        ui->sellSumLineEdit->setReadOnly(true);
        double sum=num*ui->sellPriceLineEdit->text().toInt();
        ui->sellSumLineEdit->setText(QString::number(sum));
        ui->sellOkBtn->setEnabled(true);
    }
}

void Widget::on_sellOkBtn_clicked()
{
    QString factory=ui->sellFactoryComboBox->currentText();
    QString name=ui->sellBrandComboBox->currentText();
    int value=ui->sellNumSpinBox->value();
    //sellNumSpinBox的最大值就是以前的剩余量
    int last=ui->sellNumSpinBox->maximum()-value;

    QSqlQuery query;
    //获取以前的销售量
    query.exec(QString("select sell from brand where name='%1' and factory='%2'").arg(name).arg(factory));
    query.next();
    int sell=query.value(0).toInt()+value;
    //事务操作
    QSqlDatabase::database().transaction();
    bool rtn=query.exec(QString("update brand set sell=%1,last=%2 where name='%3' and factory='%4'")
                              .arg(sell).arg(last).arg(name).arg(factory));
    if(rtn){
        QSqlDatabase::database().commit();
        QMessageBox::information(this,tr("提示"),tr("购车成功"),QMessageBox::Ok);
        this->writeXml();
        this->showDailyList();
        this->on_sellCancelBtn_clicked(true);
    }
    else{
        QSqlDatabase::database().rollback();
    }
}


void Widget::on_factoryComboBox_currentTextChanged(const QString &factoryName)
{
    if(factoryName!="请选择厂家")
        this->showChart();
}


void Widget::on_updateBtn_clicked()
{
    QString curText=ui->factoryComboBox->currentText();
    if(ui->factoryComboBox->currentText()=="请选择厂家"&&ui->factoryComboBox->currentText()==curText)
        return;
    QSplitter *p=nullptr;
    for(auto i:ui->chartPage->children()){
        if(QString(i->metaObject()->className())==QString("QSplitter")){
            p=qobject_cast<QSplitter*>(i);
            break;
        }
    }
    PieView *pie=nullptr;
    for(auto i:p->children()){
        if(QString(i->metaObject()->className())==QString("PieView")){
            pie=qobject_cast<PieView*>(i);
            break;
        }
    }
//    QPointF selectPos=pie->pos()+QPoint(pie->size().width()/3*2,pie->size().height()/2);
//    QPointF originalPos=this->cursor().pos();
//    QMouseEvent clikedHistEvent(QEvent::MouseButtonDblClick,QPointF(10,10),QPointF(0,0),
//                                Qt::LeftButton,Qt::LeftButton,Qt::NoModifier);
//    if(qApp->sendEvent(pie,&clikedHistEvent))
//        qDebug()<<true;
    pie==nullptr?void():pie->viewport()->update();
//    QPushButton *btn=new QPushButton(pie);
//    btn->setGeometry(pie->x(),pie->y(),btn->width(),btn->height());
//    btn->show();
}

